package com.yourname.xhs.util;

import java.sql.*;

public class DbUtil {


    //用properties改进？ druid


    //数据库地址
    private static String dbURL = "jdbc:mysql://localhost:3306/demo?characterEncoding=UTF-8";
    //用户名
    private static String dbUser = "root";
    //密码
    private static String dbPassword = "12345678";
    //驱动名称
    private static String jdbcName = "com.mysql.cj.jdbc.Driver";

    private static Connection conn=null;
    /**
     * 获取数据库连接
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        try {
            if(conn==null|| conn.isClosed()){
                Class.forName(jdbcName);
                conn = DriverManager.getConnection(dbURL, dbUser, dbPassword);

         }
        } catch (ClassNotFoundException e)  {
            e.printStackTrace();
        }
        catch (SQLException e){
            e.printStackTrace();
        }
        return conn;
    }


    //关闭驱动
    public static void close(ResultSet rs,PreparedStatement st, Connection conn)  {
       if(rs!=null) {
           try {
               rs.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
    }

}

//      Class.forName(jdbcName);
//Connection con = DriverManager.getConnection(dbURL, dbUser, dbPassword);
//        return con;
